<?php
/**
* @file $Id: StudentRCGrades.php 549 2007-06-04 05:10:02Z focus-sis $
* @package Focus/SIS
* @copyright Copyright (C) 2006 Andrew Schmadeke. All rights reserved.
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.txt
* Focus/SIS is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYRIGHT.txt for copyright notices and details.
*/

DrawHeader(ProgramTitle());

if($_REQUEST['values'] && $_POST['values'] && AllowEdit())
{
	if(!is_numeric($_REQUEST['mp']))
		$mp_years_RET = DBGet(DBQuery("SELECT MARKING_PERIOD_ID,SYEAR FROM ".$_REQUEST['mp']." WHERE SCHOOL_ID='".UserSchool()."'"),array(),array('MARKING_PERIOD_ID'));
//	$grades_gpa_RET = DBGet(DBQuery("SELECT ID,GPA_VALUE,SCALE_ID FROM REPORT_CARD_GRADES WHERE SCHOOL_ID='".UserSchool()."' AND SYEAR='".UserSyear()."'"),array(),array('ID'));
//	$current_credits_RET = DBGet(DBQuery("SELECT ID,CREDITS FROM STUDENT_REPORT_CARD_GRADES WHERE STUDENT_ID='".UserStudentID()."'"),array(),array('ID'));
	foreach($_REQUEST['values'] as $id=>$columns)
	{
		if($columns['PERCENT'])
			$columns['PERCENT'] = str_replace('%','',$columns['PERCENT']);
		if($id!='new')
		{
			$sql = "UPDATE STUDENT_REPORT_CARD_GRADES SET ";
							
			foreach($columns as $column=>$value)
			{
				$sql .= $column."='".str_replace("\'","''",$value)."',";
			}
			$sql = substr($sql,0,-1) . " WHERE ID='$id'";
			DBQuery($sql);
		}
		else
		{
			$sql = "INSERT INTO STUDENT_REPORT_CARD_GRADES ";

			$fields = 'ID,STUDENT_ID,SCHOOL_ID,';
			$values = db_seq_nextval('STUDENT_REPORT_CARD_GRADES_SEQ').",'".UserStudentID()."','".UserSchool()."',";

			if(!is_numeric($_REQUEST['mp']))
			{
				$fields .= 'SYEAR,';
				$values .= "'".$mp_years_RET[$columns['MARKING_PERIOD_ID']][1]['SYEAR']."',";
			}
			else
			{
				$fields .= 'SYEAR,MARKING_PERIOD_ID,';
				$values .= "'".UserSyear()."','".$_REQUEST['mp']."',";
			}

			$go = 0;
			foreach($columns as $column=>$value)
			{
				if($value)
				{
					$fields .= $column.',';
					$values .= "'".str_replace("\'","''",$value)."',";
					if($column!='GRADE_SCALE_ID' && $column!='CREDITS' && $column!='LOCATION_TITLE' && $column!='AFFECTS_GPA' && $column!='CARRIES_CREDITS' && $column!='MARKING_PERIOD_ID')
						$go = true;
				}
			}
			$sql .= '(' . substr($fields,0,-1) . ') values(' . substr($values,0,-1) . ')';
			
			if($go)
				DBQuery($sql);
		}
	}
	unset($_REQUEST['values']);
	unset($_SESSION['_REQUEST_vars']['values']);
}

if($_REQUEST['student_id'] || UserStudentID())
	DrawStudentHeader();

if($_REQUEST['modfunc']=='delete')
{
	if(DeletePrompt(_('grade')))
	{
		DBQuery("DELETE FROM STUDENT_REPORT_CARD_GRADES WHERE ID='".$_REQUEST['id']."'");
		unset($_REQUEST['modfunc']);
		// this is so that the program doesn't get confused by Modules.php setting search_modfunc by default if search screen is disabled
		if($_REQUEST['search_modfunc']=='list' && UserStudentID())
			unset($_REQUEST['search_modfunc']);
	}
}

if($_REQUEST['search_modfunc'] == 'list' || $_REQUEST['student_id'] || UserStudentID())
{
	if(!(($_REQUEST['student_id'] && $_REQUEST['student_id']!='new') || UserStudentID()) && $_REQUEST['mp'] && !is_numeric($_REQUEST['mp']))
		unset($_REQUEST['mp']);

	if(!$_REQUEST['mp'] || is_numeric($_REQUEST['mp']))
	{
		if(!$_REQUEST['mp'] && GetMP(UserMP(),'POST_START_DATE'))
			$_REQUEST['mp'] = UserMP();
		elseif(strpos(GetAllMP('QTR',UserMP()),str_replace('E','',$_REQUEST['mp']))===false && strpos(GetChildrenMP('PRO',UserMP()),"'".$_REQUEST['mp']."'")===false && GetMP(UserMP(),'POST_START_DATE'))
			$_REQUEST['mp'] = UserMP();
		
		if(!$_REQUEST['mp'] && GetMP(GetParentMP('SEM',UserMP()),'POST_START_DATE'))
			$_REQUEST['mp'] = GetParentMP('SEM',UserMP());	
	}

	$sem = GetParentMP('SEM',UserMP());
	$fy = GetParentMP('FY',$sem);
	$pro = GetChildrenMP('PRO',UserMP());
	$pros = explode(',',str_replace("'",'',$pro));
	$pro_grading = false;
	$pro_select = '';
	foreach($pros as $pro)
	{
		if(GetMP($pro,'POST_START_DATE'))
		{
			if(!$_REQUEST['mp'])
				$_REQUEST['mp'] = $pro;
			$pro_grading = true;
			$pros_arr[] = $pro;
		}
	}
	
	if(GetMP(UserMP(),'POST_START_DATE'))
	{
		$mps_arr[] = UserMP();
	}
	elseif($_REQUEST['mp']==UserMP())
		$_REQUEST['mp'] = $sem;
	
	if(GetMP($sem,'POST_START_DATE'))
		$mps_arr[] = $sem;
	if(GetMP($fy,'POST_START_DATE'))
		$mps_arr[] = $fy;
	
	if($pro_grading)
	{
		foreach($pros_arr as $mp)
			$mps_arr[] = $mp;
	}
	
	$tmp_REQUEST = $_REQUEST;
	unset($tmp_REQUEST['mp']);
	
	// this is so that the program doesn't get confused by Modules.php setting search_modfunc by default if search screen is disabled
	if($tmp_REQUEST['search_modfunc']=='list' && UserStudentID())
		unset($tmp_REQUEST['search_modfunc']);

	$tmp_PHP_SELF = PreparePHP_SELF($tmp_REQUEST);
	if(count($mps_arr))
	{
		foreach($mps_arr as $mp)
		{
			if($_REQUEST['mp']!==$mp)
			{
				$tabcolor = 'DFDFDF';
				$textcolor = '666666';
			}
			else
			{
				$tabcolor = Preferences('HIGHLIGHT');
				$textcolor = 'FFFFFF';
			}

			$header .= '<TD width=10></TD><TD>'.DrawTab(GetMP($mp),$tmp_PHP_SELF.'&amp;mp='.$mp.'&amp;LO_index='.$_REQUEST['LO_index'],$tabcolor,$textcolor,'_circle',array('tabcolor'=>Preferences('HIGHLIGHT'),'textcolor'=>'FFFFFF')).'</TD>';
			$tabs[] = array('title'=>GetMP($mp),'link'=>$tmp_PHP_SELF.'&amp;mp='.$mp.'&amp;LO_index='.$_REQUEST['LO_index']);
			$mp_tables[GetMP($mp,'TABLE')] = true;
		}

		if(count($mp_tables) && (((UserStudentID() || $_REQUEST['student_id']) && ($_REQUEST['search_modfunc']!='list' || $_FOCUS['modules_search'])) || User('PROFILE')=='parent' || User('PROFILE')=='student'))
		{
			$header .= '<TD width=10> &nbsp; </TD><TD bgcolor=black width=1></TD>';
			foreach($mp_tables as $table=>$true)
			{
				if($_REQUEST['mp']!==$table)
				{
					$tabcolor = 'DFDFDF';
					$textcolor = '666666';
				}
				else
				{
					$tabcolor = Preferences('HIGHLIGHT');
					$textcolor = 'FFFFFF';
				}

				switch($table)
				{
					case 'SCHOOL_YEARS':
						$mp_title = _('All Years');
					break;
					
					case 'SCHOOL_SEMESTERS':
						$mp_title = _('All Semesters');
					break;
					
					case 'SCHOOL_QUARTERS':
						$mp_title = _('All Quarters');
					break;
					
					case 'SCHOOL_PROGRESS_PERIODS':
						$mp_title = _('All Progress Periods');
					break;
				}
				$header .= '<TD width=10></TD><TD>'.DrawTab($mp_title,$tmp_PHP_SELF.'&amp;mp='.$table.'&amp;LO_index='.$_REQUEST['LO_index'],$tabcolor,$textcolor,'_circle',array('tabcolor'=>Preferences('HIGHLIGHT'),'textcolor'=>'FFFFFF')).'</TD>';
				$tabs[] = array('title'=>$mp_title,'link'=>$tmp_PHP_SELF.'&amp;mp='.$table.'&amp;LO_index='.$_REQUEST['LO_index']);
			}
		}
		elseif(UserStudentID() || $_REQUEST['student_id'])
			$header .= _('There are no marking periods available for taking grades.');
		
		if(!$_REQUEST['_FOCUS_PDF'] && (UserStudentID() || $_REQUEST['student_id']) && $_REQUEST['modfunc']!='delete')
		{
			$comments_RET = DBGet(DBQuery("SELECT ID,TITLE FROM REPORT_CARD_COMMENTS WHERE SCHOOL_ID='".UserSchool()."' AND SYEAR='".UserSyear()."' ORDER BY TITLE"));
			foreach($comments_RET as $comment)
				$tipmessage .= $comment['TITLE'].'<BR>';
			$tipmessage = button('comment',_('Comment Codes'),'# onClick=\'stm(["'._('Report Card Comments').'","'.$tipmessage.'"],["white","#333366","","","",,"black","#e8e8ff","","","",,,,2,"#333366",2,,,,,"",5,3,50,50]);\'','');
			echo '<FORM style="display:inline;" action=Modules.php?modname='.$_REQUEST['modname'].'&mp='.$_REQUEST['mp'].'&LO_index='.$_REQUEST['LO_index'].' method=POST>';
		}
	}
	if(!$_REQUEST['_FOCUS_PDF'] && (UserStudentID() || $_REQUEST['student_id']) && $_REQUEST['modfunc']!='delete')
		$right = '<TABLE style="display:inline;"><TR><TD>'.$tipmessage.'</TD><TD width=15> &nbsp; </TD><TD>'.SubmitButton(_('Save')).'</TD></TR></TABLE>';
	if($_REQUEST['search_modfunc']=='list' && (!UserStudentID() || $_REQUEST['bottom_back']))
		echo TabsHeader($header);
	elseif(UserStudentID() && $_REQUEST['modfunc']!='delete')
	{
		if(is_numeric($_REQUEST['mp']))
		{
			// set this variable for the sake of _roundGPA();
			$THIS_RET['SGC_STUDENT_ID'] = true;
			
			$gpa_RET = DBGet(DBQuery('SELECT sgc.GPA,sgc.WEIGHTED_GPA,sgc.CUMULATIVE_GPA,sgc.CUMULATIVE_WEIGHTED_GPA,sgc.CLASS_RANK,'."(SELECT AVG(asrcg.PERCENT)/100 FROM STUDENT_REPORT_CARD_GRADES asrcg WHERE asrcg.STUDENT_ID=sgc.STUDENT_ID AND asrcg.MARKING_PERIOD_ID='".$_REQUEST['mp']."') AS AVERAGE_GRADE FROM STUDENT_GPA_CALCULATED sgc WHERE sgc.MARKING_PERIOD_ID='".$_REQUEST['mp']."' AND sgc.STUDENT_ID='".UserStudentID()."'"));
			$left = '<TABLE cellpadding=4>';
			$left .= '<TR><TD align='.ALIGN_RIGHT.'><B>'.GetMP($_REQUEST['mp']).' '._('GPA').':</B></TD><TD>'._roundGPA($gpa_RET[1]['GPA']).'</TD><TD align='.ALIGN_RIGHT.'><B>'._('Cumulative GPA').':</B></TD><TD>'._roundGPA($gpa_RET[1]['CUMULATIVE_GPA']).'</TD></TR>';
			if(SystemPreferences('WEIGHTED_GPA'))
				$left .= '<TR><TD align='.ALIGN_RIGHT.'><B>'.GetMP($_REQUEST['mp']).' '._('Weighted GPA').':</B></TD><TD>'._roundGPA($gpa_RET[1]['WEIGHTED_GPA']).'</TD><TD align='.ALIGN_RIGHT.'><B>'._('Cumulative Weighted GPA').':</B></TD><TD>'._roundGPA($gpa_RET[1]['CUMULATIVE_WEIGHTED_GPA']).'</TD></TR>';
			$left .= '<TR><TD align='.ALIGN_RIGHT.'><B>'.GetMP($_REQUEST['mp']).' '._('Class Rank').':</B></TD><TD>'.$gpa_RET[1]['CLASS_RANK'].'</TD><TD></TD></TR>';
			if(SystemPreferences('REPORT_CARD')!='grade')
				$left .= '<TR><TD align='.ALIGN_RIGHT.'><B>'.GetMP($_REQUEST['mp']).' '._('Average Percent Grade').':</B></TD><TD>'.$gpa_RET[1]['AVERAGE_PERCENT'].'</TD><TD></TD></TR>';
			$left .= '</TABLE>';
		}
		else
		{
			// set this variable for the sake of _roundGPA();
			$THIS_RET['SGC_STUDENT_ID'] = true;

			if($_REQUEST['mp']=='SCHOOL_QUARTERS')
				$mp = UserMP();
			elseif($_REQUEST['mp']=='SCHOOL_YEARS')
				$mp = GetParentMP('FY',GetParentMP('SEM',UserMP()));
			elseif($_REQUEST['mp']=='SCHOOL_SEMESTERS')
				$mp = GetParentMP('SEM',UserMP());
	
			$gpa_RET = DBGet(DBQuery("SELECT sgc.GPA,sgc.WEIGHTED_GPA,sgc.CUMULATIVE_GPA,sgc.CUMULATIVE_WEIGHTED_GPA,sgc.CLASS_RANK FROM STUDENT_GPA_CALCULATED sgc WHERE sgc.MARKING_PERIOD_ID='".$mp."' AND sgc.STUDENT_ID='".UserStudentID()."'"));
			
			$left = '<TABLE cellpadding=4>';
			$left .= '<TR><TD align='.ALIGN_RIGHT.'><B>'._('Cumulative GPA').':</B></TD><TD>'._roundGPA($gpa_RET[1]['CUMULATIVE_GPA']).'</TD></TR>';
			if(SystemPreferences('WEIGHTED_GPA'))
				$left .= '<TR><TD align='.ALIGN_RIGHT.'><B>'._('Cumulative Weighted GPA').':</B></TD><TD>'._roundGPA($gpa_RET[1]['CUMULATIVE_WEIGHTED_GPA']).'</TD></TR>';
			$left .= '<TR><TD align='.ALIGN_RIGHT.'><B> '._('Class Rank').':</B></TD><TD>'.$gpa_RET[1]['CLASS_RANK'].'</TD><TD></TD></TR>';
			$left .= '</TABLE>';
		}
		echo DrawHeader($left,$right);
	}
}

/*Widgets('course');
Widgets('gpa');
Widgets('class_rank');
Widgets('letter_grade');
*/
Widgets('all');

$extra['SELECT'] .= ',sgc.STUDENT_ID AS SGC_STUDENT_ID,sgc.GPA,sgc.WEIGHTED_GPA,sgc.CUMULATIVE_GPA,sgc.CUMULATIVE_WEIGHTED_GPA,sgc.CLASS_RANK,'."(SELECT AVG(asrcg.PERCENT)/100 FROM STUDENT_REPORT_CARD_GRADES asrcg WHERE asrcg.STUDENT_ID=ssm.STUDENT_ID AND asrcg.MARKING_PERIOD_ID='$_REQUEST[mp]') AS AVERAGE_GRADE";

if(strpos($extra['FROM'],'STUDENT_GPA_CALCULATED sgc')===false)
{
	$extra['FROM'] = " LEFT OUTER JOIN STUDENT_GPA_CALCULATED sgc ON (sgc.STUDENT_ID=ssm.STUDENT_ID AND sgc.MARKING_PERIOD_ID='".$_REQUEST['mp']."')" .$extra['FROM'];
}
$extra['columns_after'] = array('GPA'=>_('Unweighted GPA'),'WEIGHTED_GPA'=>_('Weighted GPA'),'CUMULATIVE_GPA'=>_('Cumulative GPA'),'CUMULATIVE_WEIGHTED_GPA'=>_('Cumulative Weighted GPA'),'CLASS_RANK'=>_('Class Rank'),'AVERAGE_GRADE'=>_('Average Percent Grade'));
$extra['functions'] = array('GPA'=>'_roundGPA','WEIGHTED_GPA'=>'_roundGPA','CUMULATIVE_GPA'=>'_roundGPA','CUMULATIVE_WEIGHTED_GPA'=>'_roundGPA','CLASS_RANK'=>'_NA','AVERAGE_GRADE'=>'Percent');

if(SystemPreferences('WEIGHTED_GPA')!='Y')
{
	unset($extra['columns_after']['WEIGHTED_GPA']);
	$extra['columns_after']['GPA'] = _('GPA');
	unset($extra['columns_after']['CUMULATIVE_WEIGHTED_GPA']);
}

if(User('PROFILE')=='parent' || User('PROFILE')=='student')
	$_REQUEST['search_modfunc'] = 'list';

if($_REQUEST['student_id']=='new')
	unset($_REQUEST['student_id']);
Search('student_id',$extra);

if(UserStudentID() && $_REQUEST['modfunc']!='delete')
{
	$grade_codes_RET = DBGet(DBQuery("SELECT ID,TITLE,GPA_VALUE,DEFAULT_BREAKOFF,SCALE_ID,CREDITS FROM REPORT_CARD_GRADES WHERE SYEAR='".UserSyear()."' AND SCHOOL_ID='".UserSchool()."' ORDER BY SORT_ORDER"),array(),array('SCALE_ID'));
	echo '<script language=javascript>
	function makeGpaValue(id)
	{
		grade_codes = {};
		no_credits = {};
	';
	foreach($grade_codes_RET as $scale_id=>$codes)
	{
		$obj = $no_credits_obj = '';
		foreach($codes as $code)
		{
			$obj .= ', "'.$code['TITLE'].'":'.$code['GPA_VALUE'];
			if($code['CREDITS']!='Y')
				$no_credits_obj .= ', "'.$code['TITLE'].'":true';
			else
				$no_credits_obj .= ', "'.$code['TITLE'].'":false';			
		}
		echo "grade_codes['".$scale_id."'] = {".substr($obj,1)."};\n";
		echo "no_credits['".$scale_id."'] = {".substr($no_credits_obj,1)."};\n";
	}
	reset($grade_codes_RET);
	echo '
		credits = document.getElementById(\'inputvalues[\'+id+\'][CREDITS]\').value;
		code = document.getElementById(\'inputvalues[\'+id+\'][GRADE_TITLE]\').value;
		if(document.getElementById(\'inputvalues[\'+id+\'][GRADE_SCALE_ID]\'))
			scale_id = document.getElementById(\'inputvalues[\'+id+\'][GRADE_SCALE_ID]\').options[document.getElementById(\'inputvalues[\'+id+\'][GRADE_SCALE_ID]\').selectedIndex].value;
		else
			scale_id = "'.key($grade_codes_RET).'";
		if(code && (grade_codes[scale_id][code] || grade_codes[scale_id][code]==0))
		{
			document.getElementById(\'inputvalues[\'+id+\'][GPA_POINTS]\').value = grade_codes[scale_id][code] * credits;
';
	if(SystemPreferences('WEIGHTED_GPA')=='Y')
		echo '	document.getElementById(\'inputvalues[\'+id+\'][WEIGHTED_GPA_POINTS]\').value = grade_codes[scale_id][code] * credits;';
		echo ' if(no_credits[scale_id][code])
					document.getElementById(\'inputvalues[\'+id+\'][CARRIES_CREDITS]\').checked = false;
				else
					document.getElementById(\'inputvalues[\'+id+\'][CARRIES_CREDITS]\').checked = true;';
	echo '
		}
		return;
	}
	';
	echo '
	function makeGrade(percent,id)
	{
		percent = percent.replace("%","");
		if(document.getElementById(\'inputvalues[\'+id+\'][GRADE_SCALE_ID]\'))
			scale_id = document.getElementById(\'inputvalues[\'+id+\'][GRADE_SCALE_ID]\').options[document.getElementById(\'inputvalues[\'+id+\'][GRADE_SCALE_ID]\').selectedIndex].value;
		else
			scale_id = "'.key($grade_codes_RET).'";
		grade_values = new Array;
		grade_titles = new Array;
	';

	foreach($grade_codes_RET as $scale_id=>$codes)
	{
		echo "grade_values[".$scale_id."] = new Array;";
		echo "grade_titles[".$scale_id."] = new Array;";
		$i = 0;
		
		foreach($codes as $grade)
		{
			if(is_numeric($grade['DEFAULT_BREAKOFF']))
			{
				echo "grade_values[".$scale_id."][".$i."] = ".$grade['DEFAULT_BREAKOFF'].";";
				echo "grade_titles[".$scale_id."][".$i."] = '".$grade['TITLE']."';";
				$i++;
			}
		}
	}
	echo '
		for(i=0;i<grade_values[scale_id].length;i++)
		{
			if(percent>=grade_values[scale_id][i])
			{
				document.getElementById(\'inputvalues[\'+id+\'][GRADE_TITLE]\').value = grade_titles[scale_id][i];
				makeGpaValue(id);
				return;
			}
		}
	}

	courses = new Array;
';
	$courses_RET = DBGet(DBQuery("SELECT COURSE_ID,TITLE,SHORT_NAME FROM COURSES WHERE SYEAR='".UserSyear()."' AND SCHOOL_ID='".UserSchool()."'"));
	foreach($courses_RET as $course)
	{
		if($course['SHORT_NAME'])
			echo "courses['".$course['SHORT_NAME']."'] = '".str_replace("'","\'",$course['TITLE'])."';";
	}

	echo '
	function makeCourse(course_num,id)
	{
		if(document.getElementById(\'innerdivvalues[\'+id+\'][COURSE_TITLE]\'))
			document.getElementById(\'innerdivvalues[\'+id+\'][COURSE_TITLE]\').onclick();
		if(courses[course_num])
			document.getElementById(\'inputvalues[\'+id+\'][COURSE_TITLE]\').value = courses[course_num];
	}
	
	function clickAllBoxes(id)
	{
		if(document.getElementById(\'innerdivvalues[\'+id+\'][GRADE_TITLE]\'))
			document.getElementById(\'innerdivvalues[\'+id+\'][GRADE_TITLE]\').onclick();
		if(document.getElementById(\'innerdivvalues[\'+id+\'][CARRIES_CREDITS]\'))
			document.getElementById(\'innerdivvalues[\'+id+\'][CARRIES_CREDITS]\').onclick();
		if(document.getElementById(\'innerdivvalues[\'+id+\'][CREDITS]\'))
			document.getElementById(\'innerdivvalues[\'+id+\'][CREDITS]\').onclick();
		if(document.getElementById(\'innerdivvalues[\'+id+\'][GRADE_SCALE_ID]\'))
			document.getElementById(\'innerdivvalues[\'+id+\'][GRADE_SCALE_ID]\').style.display="inline";
		if(document.getElementById(\'innerdivvalues[\'+id+\'][GPA_POINTS]\'))
			document.getElementById(\'innerdivvalues[\'+id+\'][GPA_POINTS]\').onclick();';
	if(SystemPreferences('WEIGHTED_GPA')=='Y')
		echo '
		if(document.getElementById(\'innerdivvalues[\'+id+\'][WEIGHTED_GPA_POINTS]\'))
			document.getElementById(\'innerdivvalues[\'+id+\'][WEIGHTED_GPA_POINTS]\').onclick();';
echo '
	}
	</script>';

	$functions = array('LOCATION_TITLE'=>'_makeText','GRAD_SUBJECT_ID'=>'_makeSubject','COURSE_NUM'=>'_makeText','COURSE_TITLE'=>'_makeText','PERCENT'=>'_makeText','GRADE_TITLE'=>'_makeText','COMMENT'=>'_makeText','CREDITS'=>'_makeText','CARRIES_CREDITS'=>'_makeCheckbox','GPA_POINTS'=>'_makeText','AFFECTS_GPA'=>'_makeCheckbox','WEIGHTED_GPA_POINTS'=>'_makeText');
	
	if(is_numeric($_REQUEST['mp']))
		$grades_RET = DBGet(DBQuery("SELECT ID,SYEAR,MARKING_PERIOD_ID,COURSE_TITLE,COURSE_NUM,GRADELEVEL_TITLE,GRAD_SUBJECT_ID,GRADE_SCALE_ID,LOCATION_TITLE,REPORT_CARD_GRADE_ID,GRADE_TITLE,PERCENT,CREDITS,CARRIES_CREDITS,MODIFIED_DATE,MODIFIED_STAFF_ID,AFFECTS_GPA,GPA_POINTS,WEIGHTED_GPA_POINTS,COMMENT FROM STUDENT_REPORT_CARD_GRADES WHERE STUDENT_ID='".UserStudentID()."' AND MARKING_PERIOD_ID='".$_REQUEST['mp']."' ORDER BY COURSE_TITLE"),$functions);
	elseif($_REQUEST['mp'])
	{
		unset($mps);
		$mp_id_RET = DBGet(DBQuery("SELECT MARKING_PERIOD_ID FROM ".$_REQUEST['mp']." WHERE SCHOOL_ID='".UserSchool()."'"));
		foreach($mp_id_RET as $mp)
			$mps .= ",'".$mp['MARKING_PERIOD_ID']."'";
		$mps = substr($mps,1);
		$functions['MARKING_PERIOD_ID'] = '_makeMarkingPeriod';
		$grades_RET = DBGet(DBQuery("SELECT g.ID,g.SYEAR,g.MARKING_PERIOD_ID,g.COURSE_TITLE,g.COURSE_NUM,g.GRADELEVEL_TITLE,g.GRAD_SUBJECT_ID,g.GRADE_SCALE_ID,g.LOCATION_TITLE,g.REPORT_CARD_GRADE_ID,g.GRADE_TITLE,g.PERCENT,g.CREDITS,g.CARRIES_CREDITS,g.MODIFIED_DATE,g.MODIFIED_STAFF_ID,g.GPA_POINTS,g.WEIGHTED_GPA_POINTS,g.COMMENT,g.AFFECTS_GPA FROM STUDENT_REPORT_CARD_GRADES g,".$_REQUEST['mp']." m WHERE m.MARKING_PERIOD_ID=g.MARKING_PERIOD_ID AND g.STUDENT_ID='".UserStudentID()."' AND g.MARKING_PERIOD_ID IN (".$mps.") ORDER BY g.SYEAR ASC,m.SORT_ORDER,g.COURSE_TITLE"),$functions);
	}

	$columns = array('GRAD_SUBJECT_ID'=>_('Subject'),'COURSE_NUM'=>_('Course Number'),'COURSE_TITLE'=>_('Course'),'PERCENT'=>_('Percent'),'GRADE_TITLE'=>_('Grade'),'CREDITS'=>_('Credits'),'CARRIES_CREDITS'=>_('Carries Credits'),'GPA_POINTS'=>_('GPA Points'),'AFFECTS_GPA'=>_('Affects GPA'),'WEIGHTED_GPA_POINTS'=>_('Weighted GPA Points'),'LOCATION_TITLE'=>_('School'),'COMMENT'=>_('Comments'));
	if(SystemPreferences('REPORT_CARD')=='grade')
		unset($columns['PERCENT']);
	if(!is_numeric($_REQUEST['mp']))
		$columns = array('MARKING_PERIOD_ID'=>_('Marking Period')) + $columns;
	if(SystemPreferences('WEIGHTED_GPA')!='Y')
		unset($columns['WEIGHTED_GPA_POINTS']);

	$link['add']['html'] = array('MARKING_PERIOD_ID'=>_makeMarkingPeriod('','MARKING_PERIOD_ID'),'LOCATION_TITLE'=>_makeText('','LOCATION_TITLE'),'GRAD_SUBJECT_ID'=>_makeSubject('','GRAD_SUBJECT_ID'),'COURSE_NUM'=>_makeText('','COURSE_NUM'),'COURSE_TITLE'=>_makeText('','COURSE_TITLE'),'PERCENT'=>_makeText('','PERCENT'),'GRADE_TITLE'=>_makeText('','GRADE_TITLE'),'CREDITS'=>_makeText('','CREDITS'),'CARRIES_CREDITS'=>_makeCheckbox('','CARRIES_CREDITS'),'GPA_POINTS'=>_makeText('','GPA_POINTS'),'WEIGHTED_GPA_POINTS'=>_makeText('','WEIGHTED_GPA_POINTS'),'AFFECTS_GPA'=>_makeCheckbox('','AFFECTS_GPA'),'COMMENT'=>_makeText('','COMMENT'));
	$link['remove']['link'] = "Modules.php?modname=$_REQUEST[modname]&modfunc=delete&mp=$_REQUEST[mp]&LO_index=".$_REQUEST['LO_index'];
	$link['remove']['variables'] = array('id'=>'ID');
	$selected_tab = $tmp_PHP_SELF.'&amp;mp='.$_REQUEST['mp'].'&amp;LO_index='.$_REQUEST['LO_index'];
	echo '<BR>';
	ListOutput($grades_RET,$columns,'','',$link,array(),array('middle'=>WrapTabs($tabs,$selected_tab)));
	if(!$_REQUEST['_FOCUS_PDF'])
		echo '<CENTER><BR>'.SubmitButton(_('Save')).'</CENTER></FORM>';	
}

function _roundGPA($gpa,$column)
{	global $THIS_RET;

	return _NA(round($gpa,3));
}

function _NA($value,$column='')
{	global $THIS_RET;

	if($THIS_RET['SGC_STUDENT_ID'])
		return $value;
	else
		return _('N/A');
}

function _makeText($value,$column)
{	global $THIS_RET;
	
	$div = 'force';
	if($THIS_RET['ID'])
		$id = $THIS_RET['ID'];
	else
	{
		$id = 'new';
		$div = false;
	}

	if($column=='PERCENT')
	{
		$value .= '%';
		if($value=='%')
			$div = false;
	}
	elseif($column=='CREDITS' && strlen($value)==0)
	{
		$value = SystemPreferences('DEFAULT_CREDITS');
		$div = false;
	}
	elseif($column=='LOCATION_TITLE' && $id=='new')
		$value = GetSchool(UserSchool());
	elseif($column=='COURSE_NUM' && !$value && $id=='new')
		$extra = 'size=7 onchange="makeCourse(this.value,\''.$id.'\');"';
	elseif($column=='COURSE_NUM' && !$value)
		$extra = 'size=7 onchange="makeCourse(this.value,'.$id.');"';
	
	if(($div==false || (!$value && $value!==0)) && ($column=='PERCENT' || $column=='GPA_POINTS' || $column=='WEIGHTED_GPA' || $column=='GRADE_TITLE' || $column=='CREDITS'))
		$extra = ' size=3 ';

	if($id=='new' && ($column=='PERCENT'))
		$extra .= ' onchange="clickAllBoxes(\''.$id.'\');makeGrade(this.value,\''.$id.'\');"';
	elseif($column=='PERCENT')
		$extra .= ' onchange="clickAllBoxes('.$id.');makeGrade(this.value,'.$id.');"';
	elseif($id!='new' && ($column=='GPA_POINTS' || $column=='WEIGHTED_GPA_POINTS' || $column=='GRADE_TITLE' || $column=='CREDITS'))
		$extra .= ' onchange="clickAllBoxes('.$id.');makeGpaValue('.$id.');"';
	elseif($column=='GPA_POINTS' || $column=='WEIGHTED_GPA_POINTS' || $column=='GRADE_TITLE' || $column=='CREDITS')
		$extra .= ' onchange="clickAllBoxes(\''.$id.'\');makeGpaValue(\''.$id.'\');"';

	if($column=='GRADE_TITLE' && $id!='new')
		$extra .= ' onfocus="clickAllBoxes('.$id.');this.focus();" ';

	if($column=='GRADE_TITLE')
	{
		$scales_RET = DBGet(DBQuery("SELECT ID,TITLE FROM REPORT_CARD_GRADE_SCALES WHERE SYEAR='".UserSyear()."' AND SCHOOL_ID='".UserSchool()."' ORDER BY COALESCE(DEFAULT_SCALE,'N') DESC"));
		if(count($scales_RET)>1)
		{
			$scale_select = '<DIV id=innerdivvalues['.$id.'][GRADE_SCALE_ID] style="display:none;"><SELECT name="values['.$id.'][GRADE_SCALE_ID]">';
			foreach($scales_RET as $scale)
				$scale_select .= '<OPTION value='.$scale['ID'].($scale['ID']==$THIS_RET['GRADE_SCALE_ID']?' SELECTED':'').'>'.$scale['TITLE'].'</OPTION>';
	
			$scale_select .= '</SELECT></DIV>';
		}
	}
	else
		$scale_select = '';
	
	return TextInput($value,'values['.$id.']['.$column.']','',$extra,$div).$scale_select."\n";
}

function _makeSubject($value,$column)
{	global $THIS_RET,$subjects_arr;

	if($THIS_RET['ID'])
		$id = $THIS_RET['ID'];
	else
		$id = 'new';

	if(!$subjects_arr)
	{
		$subjects_RET = DBGet(DBQuery("SELECT ID,TITLE FROM GRAD_SUBJECTS WHERE SCHOOL_ID='".UserSchool()."' ORDER BY SORT_ORDER"));
		foreach($subjects_RET as $subject)
			$subjects_arr[$subject['ID']] = $subject['TITLE'];
	}
	
	return SelectInput($value,'values['.$id.']['.$column.']','',$subjects_arr);
}

function _makeMarkingPeriod($value,$column)
{	global $THIS_RET,$_FOCUS;

	if($THIS_RET['ID'])
		$id = $THIS_RET['ID'];
	else
		$id = 'new';

	if($_REQUEST['mp'] && !is_numeric($_REQUEST['mp']) && !$_FOCUS['marking_periods'])
	{
		$marking_periods_RET = DBGet(DBQuery("SELECT SYEAR,MARKING_PERIOD_ID,TITLE FROM ".$_REQUEST['mp']." WHERE SCHOOL_ID='".UserSchool()."' ORDER BY SYEAR DESC,SORT_ORDER DESC"));
		foreach($marking_periods_RET as $mp)
			$marking_periods_arr[$mp['MARKING_PERIOD_ID']] = $mp['SYEAR'].((SystemPreferences('SYEAR_TITLE')=='YYYY-YYYY')?'-'.($mp['SYEAR']+1):'').' '.$mp['TITLE'];
	}
	
	return SelectInput($value,'values['.$id.']['.$column.']','',$marking_periods_arr,false);
}

function _makeCheckbox($value,$column)
{	global $THIS_RET;

	if($THIS_RET['ID'])
		$id = $THIS_RET['ID'];
	else
	{
		$id = 'new';
		$value = 'Y';
		$new = true;
	}

	return CheckboxInput($value,'values['.$id.']['.$column.']','','',$new,_('Yes'),_('No'),true,$extra);
}
?>